<template>
  <div>
    <a-modal
      v-model="visible"
      :title="`批量新增${title}`"
      :maskClosable="false"
      :width="1000"
      centered
      okText="确定"
      @ok="handleOk"
    >
      <div class="disFlxJS _mt-5">
        <div class="leftBox">
          <div class="fixedTop">
            <div class="disFlxJS linh-40">
              <div>可选{{ title }}</div>
            </div>
            <a-input-search
              v-model="queryParam.keyWord"
              size="small"
              class="_mt-5 _mb-10"
              :placeholder="`搜索${title}名称`"
              @search="refresh"
            />
          </div>
          <div class="_pl-12 _pr-12" style="flex:1;">
            <a-tree
              v-if="treeData.length"
              v-model="checkedKeys"
              checkable
              auto-expand-parent
              :tree-data="treeData"
              @check="onCheck"
            />
            <a-empty v-else description="没有可选择的项" />
          </div>
        </div>

        <div class="rightBox">
          <div class="fixedTop">
            <div class="disFlxJS linh-40">
              <div>已选择：{{ checkedList.length }}项</div>
              <div>
                <a-tooltip title="清除全部已选">
                  <a-icon type="delete" class="cup _pl-10 _pt-10 _pb-10" @click="handRemove()" />
                </a-tooltip>
              </div>
            </div>
            <a-input-search
              size="small"
              class="_mt-5 _mb-10"
              :placeholder="`搜索已选${title}名称`"
              @search="handSearch"
            />
          </div>
          <div class="_pl-12 _pr-12" style="flex:1;">
            <template v-for="item in checkedList">
              <div v-if="!item.hide" :key="item.key" class="linh-40 disFlxJS">
                <div class="ov-1" style="flex:1;">
                  {{ item.title }}
                </div>
                <div>
                  <a-icon type="close" class="cup _pl-10 _pt-10 _pb-10" @click="handRemove(item.key)" />
                </div>
              </div>
            </template>
            <a-empty v-if="!checkedList.length" description="暂无选择项" />
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { uniqBy, flattenDeep, uniq } from 'lodash-es'
import { findParentIds } from '@/utils/treeutil'

export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    api: {
      type: Function,
      default: () => {}
    }
  },
  emits: ['success'],
  data() {
    return {
      visible: false,
      // 查询参数
      queryParam: {
        keyWord: undefined
      },
      total: 0,
      initTreeData: [],
      treeData: [],
      historyCheckedKeys: [],
      checkedKeys: [], // 已选key组合
      checkedList: [] // 已选列表
    }
  },
  methods: {
    onCheck(checkedKeys, { node, checked }) {
      const _list = this.getLeafKeys(node.dataRef)
      const checkeds = uniqBy([...this.checkedList, ..._list], 'key')
      if (this.queryParam.keyWord) {
        const keys = findParentIds(this.initTreeData, 'key', node.dataRef.key)
        if (!checked) {
          this.historyCheckedKeys = this.historyCheckedKeys.filter(key => {
            return !keys.includes(key)
          })
        } else {
          this.historyCheckedKeys.push(...checkedKeys)
        }
        this.checkedList = checkeds.filter(v => this.historyCheckedKeys.includes(v.key))
      } else {
        this.checkedList = checkeds.filter(v => checkedKeys.includes(v.key))
      }
    },
    // 获取树形对象最底层集合
    getLeafKeys(tree) {
      const leafKeys = []
      function traverse(node) {
        if (Array.isArray(node.children) && node.children.length > 0) {
          node.children.forEach(child => {
            child.pid = node.key
            traverse(child)
          })
        } else {
          leafKeys.push(node)
        }
      }

      traverse(tree)
      return leafKeys
    },

    openModal() {
      this.visible = true
      this.getList()
    },
    closeModal() {
      this.visible = false
      this.checkedKeys = []
      this.checkedList = []
      this.historyCheckedKeys = []
    },

    async getList() {
      const { data } = await this.api()
      this.treeData = [...data]
      this.initTreeData = [...data]
    },
    refresh() {
      if (!this.queryParam.keyWord) {
        this.treeData = this.initTreeData
        this.checkedKeys = [...this.historyCheckedKeys]
        return
      }
      this.historyCheckedKeys = uniq([...this.historyCheckedKeys, ...this.checkedKeys])
      this.treeData = flattenDeep(
        this.initTreeData.map(forItem => {
          return this.getLeafKeys(forItem)
        })
      ).filter(item => item.title.includes(this.queryParam.keyWord))
    },
    // 清除已选
    handRemove(key) {
      if (key) {
        const item = this.checkedList.find(v => v.key === key)
        this.checkedList = this.checkedList.filter(v => v.key !== item.key)
        this.checkedKeys = this.checkedKeys.filter(v => v !== item.key && v !== item.parentKey)
        this.historyCheckedKeys = this.historyCheckedKeys.filter(v => v !== item.key && v !== item.parentKey)
      } else {
        this.checkedList = []
        this.checkedKeys = []
        this.historyCheckedKeys = []
      }
    },
    // 搜索已勾选列表
    handSearch(e) {
      this.checkedList.forEach(v => {
        this.$set(v, 'hide', !v.title.includes(e))
      })
    },
    handleOk() {
      this.$emit(
        'success',
        this.checkedList.map(item => item.key)
      )
    }
  }
}
</script>

<style lang="less" scoped>
.leftBox,
.rightBox {
  width: 48%;
  height: 468px;
  position: relative;
  overflow-y: auto;
  border: solid 1px #e5e6eb;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  .fixedTop {
    position: sticky;
    z-index: 99;
    top: 0;
    background-color: #f7f8fa;
    color: #333;
    padding-left: 12px;
    padding-right: 12px;
    flex-shrink: 0;
  }
  /deep/ .ant-checkbox-wrapper {
    display: flex;
    align-items: center;
  }
}
</style>
